<template>
    <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
        <BasicForm @register="registerForm"/>
    </BasicModal>
</template>
<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from './opmsFixResident.data';
    import {useMessage} from '/@/hooks/web/useMessage';
    import {
        createOpmsFixResident,
        updateOpmsFixResident
    } from '/@/api/resident/opmsFixResident';
    import dayjs from "dayjs";
    const emit = defineEmits(['success', 'register']);
    const isUpdate = ref(true);
    const {createMessage} = useMessage();

    const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
    });

    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        resetFields();
        setModalProps({confirmLoading: false});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            setFieldsValue({
                ...data.record,
            });
        }
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增常住居民表' : '编辑常住居民表'));

    async function handleSubmit() {
        try {
            const values = await validate();
            //处理日期格式 如果后台日期对象为LocalDate 转换后的为 YYYY-MM-DD ，但是前端的日期选择器是 YYYY-MM-DD hh:mm:ss,需要转换一下
            values['issuingDate'] = dayjs(values['issuingDate']).format("YYYY-MM-DD")
            values['birthDate'] = dayjs(values['birthDate']).format("YYYY-MM-DD")
            setModalProps({confirmLoading: true});
            if (unref(isUpdate)) {
                await updateOpmsFixResident(values);
                createMessage.success("更新成功");
            } else {
                await createOpmsFixResident(values);
                createMessage.success("创建成功");
            }
            closeModal();
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>
<script lang="ts">
    export default {name: 'OpmsFixResidentModal'};
</script>
